package com.vogue.supplymall.account.shiro.filter;

import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vogue.gear.memory.provider.IMemProvider;
import com.vogue.ssm.database.util.DealStatus;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.constant.ErrorCode;
import com.vogue.supplymall.common.domain.tool.VestUtils;
/**
 * 所有访问都过滤的过滤器
 * @author 崔岳
 *
 */
public class WholeAuthenticationFilter extends BaseFilter {

    public static final Logger LOGGER_WHOLEAUTHENTICATIONFILTER = LoggerFactory.getLogger(WholeAuthenticationFilter.class);

    private final static String ERROR_CODE_KEY = "ERRORCODE"; //错误编号关键字

    private final static String VERSIONSTR = "Version"; //版本号拼接组成字符串

    @Resource(name = "memProvider")
    private IMemProvider<Object> memProvider;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        // TODO Auto-generated method stub
        DealStatus.removeShade();
        VestUtils.clear();
        HttpServletRequest httpRequest;
        httpRequest = WebUtils.toHttp(request);
//      if(httpRequest.getMethod().equals("OPTIONS")) {
//          return true;
//      }
        
        String pname = httpRequest.getHeader("pname");
        String pver = httpRequest.getHeader("pver"); //版本号
        String psys = httpRequest.getHeader("psys"); //系统来源 ios/android/PC
        String origin = httpRequest.getHeader("originname"); //判断访问的来源

        VestUtils.setClientIp(getIpAddress(httpRequest));        
        
        if (origin != null) {
            VestUtils.setOrigin(origin);
            LOGGER_WHOLEAUTHENTICATIONFILTER.info("用户访问来源：{}", origin);
        } else {
            VestUtils.setOrigin("TEL");
            LOGGER_WHOLEAUTHENTICATIONFILTER.info("用户访问来源：手机(默认)");
        }

        if (pver == null) {
            LOGGER_WHOLEAUTHENTICATIONFILTER.error("缺少必要的系统信息：HEADER中的pver");
            if (VestUtils.isVisitFromTEL()) {
                request.setAttribute(ERROR_CODE_KEY, ErrorCode.NeedUpgrade.getCode());
                return false;
            }            
        } else {
            VestUtils.setVersion(pver);
        }

        if (psys == null) {
            LOGGER_WHOLEAUTHENTICATIONFILTER.error("缺少必要的系统信息：HEADER中的psys");
            if (VestUtils.isVisitFromTEL()) {
                request.setAttribute(ERROR_CODE_KEY, ErrorCode.NeedUpgrade.getCode());
                return false;
            }
        } else {
            VestUtils.setSystem(psys.toLowerCase());
        }
        
        if (pname != null) {
            Object platform = memProvider.get(ConstantBean.PLATFORM_PROVIDER_NAME);
            if (platform != null) {
                @SuppressWarnings("unchecked")
                Map<String, String> map = ((Map<String, Map<String, String>>) platform).get(pname);
                if (map != null) {
                    DealStatus.setShade(map.get("tname"));
                    VestUtils.setName(map.get("name"));
                    VestUtils.setTendid(map.get("code"));
                    VestUtils.setEntryMode(map.get("entrymode"));
                    VestUtils.setPayTogether(map.get("paytogether"));
                    if (VestUtils.isVisitFromTEL()) {
                        if (!VestUtils.isVersionEffectual(map.get(VestUtils.getSystem() + VERSIONSTR))) {
                            request.setAttribute(ERROR_CODE_KEY, ErrorCode.NeedUpgrade.getCode());
                            return false;
                        }
                    }                    
                }
            }
        }

        if (DealStatus.getShade() == null) {
            request.setAttribute(ERROR_CODE_KEY, ErrorCode.IllegalVisit.getCode());
//            return false;
        }

        LOGGER_WHOLEAUTHENTICATIONFILTER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        LOGGER_WHOLEAUTHENTICATIONFILTER.info(">>>>>>>>>>");
        LOGGER_WHOLEAUTHENTICATIONFILTER.info("平台代号：{}，平台名称：{}，平台编码：{}，客户端ip：{}", pname, VestUtils.getName(), DealStatus.getShade(), VestUtils.getClientIp());
        LOGGER_WHOLEAUTHENTICATIONFILTER.info(">>>>>>>>>>");
        LOGGER_WHOLEAUTHENTICATIONFILTER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        Integer errcode = (Integer) request.getAttribute(ERROR_CODE_KEY);
        ajaxResponse(request, response, errcode);
        return false;
    }

    /**
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
     * @param request
     * @return
     * @throws IOException
     */
    public final static String getIpAddress(HttpServletRequest request)  {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址

        String ip = request.getHeader("X-Forwarded-For");
        if (LOGGER_WHOLEAUTHENTICATIONFILTER.isInfoEnabled()) {
            LOGGER_WHOLEAUTHENTICATIONFILTER.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forward-For");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
                if (LOGGER_WHOLEAUTHENTICATIONFILTER.isInfoEnabled()) {
                    LOGGER_WHOLEAUTHENTICATIONFILTER.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);
                }
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
                if (LOGGER_WHOLEAUTHENTICATIONFILTER.isInfoEnabled()) {
                    LOGGER_WHOLEAUTHENTICATIONFILTER.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);
                }
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
                if (LOGGER_WHOLEAUTHENTICATIONFILTER.isInfoEnabled()) {
                    LOGGER_WHOLEAUTHENTICATIONFILTER.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);
                }
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                if (LOGGER_WHOLEAUTHENTICATIONFILTER.isInfoEnabled()) {
                    LOGGER_WHOLEAUTHENTICATIONFILTER.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);
                }
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                if (LOGGER_WHOLEAUTHENTICATIONFILTER.isInfoEnabled()) {
                    LOGGER_WHOLEAUTHENTICATIONFILTER.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);
                }
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }
}
